import React from 'react';
import { Table, Input, Form, Button, InputNumber, Divider } from 'antd';
import { Icon } from '@/pages/Recruitment/components';
import { recheckWhenError } from '@/utils/formHelper';

const EditableContext = React.createContext();
const submitCheckFiledName = 'KPISubmitCheck';
function EditableCell(props) {
    const { editing, dataIndex, title, inputType, record, index, children, ...restProps } = props;

    const renderCell = ({ getFieldDecorator }) => (
        <td {...restProps}>
            {editing ? (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                        rules: [
                            {
                                required: true,
                                message: `请输入 ${title}!`
                            }
                        ],
                        initialValue: record[dataIndex]
                    })(
                        dataIndex === 'weight' ? (
                            <InputNumber min={1} max={100} />
                        ) : (
                            <Input autoFocus={dataIndex === 'target'} maxLength={200} />
                        )
                    )}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
}

const EditableTable = props => {
    const { form: formProps, onChange } = props;
    const [editingKey, setEditingKey] = React.useState('');
    const [dataSource, setDataSource] = React.useState([]);
    const isEditing = record => record.key === editingKey;
    const cache = {
        nums: 0
    };

    React.useEffect(() => {
        onChange(dataSource);
    }, [dataSource]);

    const save = (form, key) => {
        form.validateFields(['target', 'performanceContent', 'weight'], (error, row) => {
            if (error) {
                return;
            }
            const newData = [...dataSource];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row
                });
                setDataSource(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setDataSource(newData);
                setEditingKey('');
            }
        });
        recheckWhenError(form, submitCheckFiledName);
    };

    const edit = key => {
        setEditingKey(key);
    };

    const del = record => {
        setDataSource(dataSource.filter(item => item.key !== record.key));
    };
    const cancel = record => {
        const { performanceContent, target, weight } = record;
        const flag = [performanceContent, target, weight].some(Boolean);
        if (!flag) {
            del(record);
        }
        setEditingKey('');
    };

    const columns = [
        {
            title: '绩效目标',
            dataIndex: 'target',
            width: 400,
            editable: true
        },
        {
            title: '衡量标准/关键结果',
            dataIndex: 'performanceContent',
            editable: true
        },
        {
            title: '权重(%)',
            dataIndex: 'weight',
            width: 120,
            editable: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) => {
                const editable = isEditing(record);
                if (editable) {
                    cache.nums += 1;
                }
                return editable ? (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <EditableContext.Consumer>
                            {form => <Icon title="确认" type="confirm_o" onClick={() => save(form, record.key)} />}
                        </EditableContext.Consumer>
                        <Divider type="vertical" />
                        <Icon title="取消" type="cancel_o" onClick={() => cancel(record)} />
                    </div>
                ) : (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            disabled={editingKey !== ''}
                            onClick={() => edit(record.key)}
                        />
                        <Divider type="vertical" />
                        <Icon
                            title="删除"
                            type="listfunction_delete_icon_default"
                            disabled={editingKey !== ''}
                            onClick={() => {
                                del(record);
                            }}
                        />
                    </div>
                );
            }
        }
    ];

    const components = {
        body: {
            cell: EditableCell
        }
    };

    const finalColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });

    const handleAdd = () => {
        const count = dataSource.length + 1;
        const newData = {
            key: count,
            performanceContent: '',
            target: '',
            weight: ''
        };
        setDataSource([...dataSource, newData]);
        if (!editingKey) {
            setEditingKey(count);
        }
    };

    return (
        <EditableContext.Provider value={formProps}>
            <Form.Item>
                {formProps.getFieldDecorator(submitCheckFiledName, {
                    validateTrigger: '',
                    rules: [
                        {
                            validator(_, foo, callback) {
                                if (!dataSource?.length) {
                                    callback('请至少添加一项绩效目标！');
                                    return;
                                }
                                if (cache.nums !== 0) {
                                    callback('请保存绩效目标！');
                                    return;
                                }
                                const total = dataSource.reduce((pre, curr) => pre + parseInt(curr.weight, 10), 0);

                                if (total > 100) {
                                    callback('权重累计不能超过100%！');
                                    return;
                                }
                                callback();
                            }
                        }
                    ]
                })(<Table components={components} dataSource={dataSource} columns={finalColumns} pagination={false} />)}
            </Form.Item>
            {editingKey === '' && (
                <Button block type="dashed" style={{ marginTop: 16 }} onClick={handleAdd}>
                    + 新增
                </Button>
            )}
        </EditableContext.Provider>
    );
};

export default EditableTable;
